package org.hjq.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.hjq.entity.User;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Data
@ConfigurationProperties(prefix = "jwt")
@Component
public class JwtUtil {
    //密钥
    private String secret;
    //过期时间
    private Long expiration;
    /**
     * 从数据生成令牌
     */
    private String generateToken(Map<String, Object> claims){
        Date expirationTime = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().addClaims(claims).setExpiration(expirationTime)
                .signWith(SignatureAlgorithm.HS512,secret).compact();
    }
    /**
     * 从令牌中获取数据声明
     */
    public Claims getClaimsFromToken(String token){
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }
    /**
     * 生成令牌
     */
    public String generateToken(User user){
        HashMap<String, Object> claims = new HashMap<>(2);
        claims.put(Claims.SUBJECT,user.getUsername());
        claims.put(Claims.ISSUED_AT,new Date());
        return generateToken(claims);
    }
    /**
     * 从令牌中获取数据声明
     */
    public String getUsernameFromToken(String token){
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;

    }
    /**
     * 是否过期
     */
    public Boolean isTokenExpired(String token){
        Claims claims = getClaimsFromToken(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }
    /**
     * 刷新令牌
     */
    public String refreshToken(String token){
        String refreshToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT,new Date());
            refreshToken = generateToken(claims);
        } catch (Exception e) {
            refreshToken = null;
        }
        return refreshToken;
    }
    /**
     * 验证令牌
     */
    public Boolean validateToken(String token, User user){
        String username = getUsernameFromToken(token);
        return username.equals(user.getUsername())&&!isTokenExpired(token);
    }

}
